﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using LynxBlogAPI.Models;

namespace LynxBlogAPI.Controllers
{
    public class PageDataViewController : ApiController
    {

        // GET api/pagedataview
        public List<PageDataView> Get()
        {
            LynxWebLog_Context db = new LynxWebLog_Context();
            IEnumerable<PageDataView> lpdv = null;
            IEnumerable<PageDataSelector> lpds = null;
            try {
                lpds = (from pd in db.PageDatas where pd.IsPublished == true group pd by pd.blogid into pdg select new PageDataSelector { blogid = pdg.Key, wp_page_order = pdg.Min(pd => pd.wp_page_order) });

                IEnumerable<PageData> lpd = from p in db.PageDatas join s in lpds on new { p.blogid, p.wp_page_order } equals new { s.blogid, s.wp_page_order } select p;
                lpdv = from p in lpd join b in db.BlogDatas on p.blogid equals b.blogid select new PageDataView { bd = b, pd = p };
            }
            catch (SystemException ex) {
                Debug.Print(ex.Message);
            }

            return lpdv.ToList();
        }

        // GET api/pagedataview/5
        public PageDataView Get(string blogid, string title)
        {
            LynxWebLog_Context db = new LynxWebLog_Context();
            PageDataView pdv = (from p in db.PageDatas 
                                    join b in db.BlogDatas 
                                        on p.blogid equals b.blogid 
                                where p.blogid == blogid && p.title == title 
                                select new PageDataView { pd = p, bd = b }).FirstOrDefault();
                                        
                                    
            return pdv;
        }

    }
    public class PageDataSelector
    {
        public string blogid { get; set; }
        public string wp_page_order { get; set; }

    }

}
